<script lang="ts" setup>
import type { FormInstance, DrawerProps } from 'ant-design-vue';
import { $t } from '@vben/locales';
import type { Permissions } from './types';
import { onMounted, reactive, ref, watch, computed, toRefs } from 'vue';
import { message } from 'ant-design-vue';
import { removeEmpty, removeNull } from '#/utils/common';
import ImageUpload from '#/components/ImageUpload.vue';
import { useDebounceFn } from '@vueuse/core';
import dayjs, { Dayjs } from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import type { ComponentSetting } from '../../uctoo/component_setting/types.ts';
import { uctoo_permissions, uctoo_component_setting } from '#/store';
import { useRepo } from 'pinia-orm';
import { useAxiosRepo } from '@pinia-orm/axios';
import { getUserGroupAll } from '../user_group/homeapi';
import { connectGroupHasPermission } from '../group_has_permission/homeapi';

// 加载 utc 和 timezone 插件
dayjs.extend(utc);
dayjs.extend(timezone);
const loading = ref(false);
const groupOptions = ref<any[]>([]); 
const checkedList = ref<any[]>([]);
const props = defineProps<{
  mode: 'add' | 'edit';
  record: Permissions | null;
  visible: boolean;
  componentSettingData: ComponentSetting[];
  ids?:(string[] | number[]);
}>();

// 计算属性判断空值
const isIdsEmpty = computed(() => 
  !props.ids || props.ids.length === 0
);

const emit = defineEmits(['update:visible', 'success']);

const ENTITY_PROXY: { [K in keyof Permissions]: null } = {
id: null,
permission_name: null,
level: null,
icon: null,
module: null,
component: null,
redirect: null,
type: null,
hidden: null,
weight: null,
creator: null,
created_at: null,
updated_at: null,
deleted_at: null,
keepalive: null,
path: null,
title: null,
parent_id: null,
meta: null,
method: null,
};
 
// 获取有效字段选项
const getFieldOptions = () => {
  // 排除系统字段
  const EXCLUDED_FIELDS = ['id', 'creator', 'created_at', 'updated_at', 'deleted_at'] as const;
  
  return (Object.keys(ENTITY_PROXY) as Array<keyof Permissions>).filter(
    field => !EXCLUDED_FIELDS.includes(field as typeof EXCLUDED_FIELDS[number])
  );
};
const formRef = ref<FormInstance>();


const formState = reactive<Record<keyof Permissions, any>>(
  Object.fromEntries(
    getFieldOptions().map(k => [k, '']) // 初始化所有有效字段
  ) as Record<keyof Permissions, any>
);
     // 用户选择的表单项，初始化为表单所有项或根据需求预选一些项
    const selectedFormItems = ref<Array<keyof Permissions>>(Object.keys(formState) as Array<keyof Permissions>);
    const handleFormItemChange = () => {
      console.log('Selected columns:', selectedFormItems.value);
    }; 

/** rules */
const rules = {
 permission_name: [{ message: $t('page.Required'), required: true }],
};


watch(
  () => props.record,
  (newVal) => {
      formState.permission_name = props.record?.name
      if (props.record?.groups && props.record?.groups.length > 0) {
        checkedList.value = props.record?.groups.map(group => group.group_id);     //props.record?.groups.map(group => group.group_id);
      } else {
        // 处理groups为空或未定义的情况
        checkedList.value = [];
      } 
    
  },
  { immediate: true },
);

const handleOk = () => {
  console.log(formState);
    interface Formated {
      permission_name?: string,
      group_id?: string,
      status: 1
     };

    const formatedFormState: Formated = {
      permission_name: formState.permission_name,
      group_id: JSON.stringify(checkedList.value),
      status: 1
     };

  formRef.value?.validate().then(async () => {
    try {
      if (props.mode === 'add') {
        await connectGroupHasPermission(removeEmpty(formatedFormState));
        message.success($t('page.AddSuccess'));
      } else {
        await connectGroupHasPermission(removeNull(formatedFormState));
          message.success($t('page.EditSuccess'));        
      }
      emit('success');
    } catch {
      message.error($t('page.EditFailed'));
    }
  });
};

const handleCancel = () => {
  emit('update:visible', false);
};


 
const onCheckboxChange = (checkedValues: string) => {
  console.log('选中的值：', checkedValues);
  // 处理复选框选择变化的逻辑
};

const fetchData = async () => {
  loading.value = true;
  try {
    const resUserGroupAll = await getUserGroupAll();
    console.log(resUserGroupAll);
    groupOptions.value = resUserGroupAll.map((item) => ({
      label: item.group_name,
      value: item.id,
    }));
  } catch {
    message.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchData();
});
</script>

<template>
  <a-modal
    :open="visible"
    :title="mode === 'add' ? $t('page.Add') : formState.permission_name+$t('page.GrantPermissionsToUserGroups')"
    @cancel="handleCancel"
    @ok="handleOk"
  >

  <a-form ref="formRef" :model="formState" :rules="rules">
    <a-form-item :label="$t('database.user_group')" name="group">
    <a-checkbox-group v-model:value="checkedList" @change="onCheckboxChange">
      <a-row>
        <a-col :span="8" v-for="item in groupOptions" :key="item.value">
          <a-checkbox :value="item.value">{{ item.label }}</a-checkbox>
        </a-col>
      </a-row>
    </a-checkbox-group>
  </a-form-item>
<a-form-item :label="$t('database_column.uctoo.permissions.permission_name')" name="permission_name" v-show="false">
        <a-input v-model:value="formState.permission_name" />
      </a-form-item></a-form>

  </a-modal>
</template>
